/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DAO.DonHangDAO;
import DAO.ProductCategoryDAO;
import DAO.ProductDAO;
import DAO.SupplierDAO;

import DAO.UserDAO;
import Pojo.LoaiSanPham;
import Pojo.NhaCungCap;
import Pojo.SanPham;
import Pojo.User;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author HDKhanh
 */
public class C_Product extends HttpServlet {

    final private String homePage = "index.jsp";
    final private String failLoginPage = "failLogin.jsp";
    final private String menuPage = "menuFunction.jsp";
    final private String qlndPage = "manageUser.jsp";
    final private String insert_updatePage = "insert_updateUser.jsp";
    final private String insert_updatePagePro = "insert_updatePro.jsp";
    final private String insert_updatePageCus = "insert_updateUserCus.jsp";
    final private String insert_updatePageProCate = "insert_updateProCate.jsp";
    final private String notAlowPage = "notAlow.jsp";
    final private String productPage = "manageProduct.jsp";
    final private String productCategoryPage = "manageProductCategory.jsp";
    final private String billPage = "manageBill.jsp";
    final private String customerPage = "manageCustomer.jsp";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        //PrintWriter out=response.getWriter();
        try {
            //xu li up anh cho san pham
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) { // Create a factory for disk-based file items 
                FileItemFactory factory = new DiskFileItemFactory();
                // Create a new file upload handler 
                ServletFileUpload upload = new ServletFileUpload(factory);
                try {
                    // Parse the request 
                    List /* FileItem */ items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    String fileName = "", masp = "", txtsp = "", txtdongia = "", txtsoluong = "", maloaisp = "", mancc = "";
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            fileName = item.getName();
                            if (!fileName.equals("")) {
                                String root = getServletContext().getRealPath("/");
                                File path = new File(root + "/skin/images/sp");
                                if (!path.exists()) {
                                    boolean status = path.mkdirs();
                                }
                                File uploadedFile = new File(path + "/" + fileName);
                                System.out.println(uploadedFile.getAbsolutePath());
                                item.write(uploadedFile);
                            }
                        } else {
                            if (item.getFieldName().equals("masp")) {
                                masp = item.getString();
                            } else if (item.getFieldName().equals("txtsp")) {
                                txtsp = item.getString("utf-8");
                            } else if (item.getFieldName().equals("txtdongia")) {
                                txtdongia = item.getString();
                            } else if (item.getFieldName().equals("txtsoluong")) {
                                txtsoluong = item.getString();
                            } else if (item.getFieldName().equals("maloaisp")) {
                                maloaisp = item.getString();
                            } else if (item.getFieldName().equals("mancc")) {
                                mancc = item.getString();
                            }
                        }
                    }
                    if (!masp.equals("")) {
                        int pid = Integer.parseInt(masp);
                        SanPham p = ProductDAO.GetInfo(pid);
                        if (p != null) {
                            p.setTensp(txtsp);
                            p.setDongia(Float.parseFloat(txtdongia));
                            p.setSoluong(Integer.parseInt(txtsoluong));
                            LoaiSanPham lsp = ProductCategoryDAO.GetInfo(Integer.parseInt(maloaisp));
                            p.setLoaiSanPham(lsp);
                            NhaCungCap ncc = SupplierDAO.GetInfo(Integer.parseInt(mancc));
                            p.setNhaCungCap(ncc);
                            if (!fileName.equals("")) {
                                p.setHinhanh(fileName);
                            }
                            ProductDAO.Update(p);
                            String url = "C_Product?btAction=Pro_Search&txtSearch=";
                            RequestDispatcher rd = request.getRequestDispatcher(url);
                            rd.forward(request, response);
                        }
                    } else {
                        SanPham p = new SanPham();
                        p.setTensp(txtsp);
                        p.setDongia(Float.parseFloat(txtdongia));
                        p.setSoluong(Integer.parseInt(txtsoluong));
                        p.setHinhanh(fileName);
                        int mancc1 = Integer.parseInt(mancc);
                        int malsp = Integer.parseInt(maloaisp);
                        ProductDAO.Insert(p, mancc1, malsp);
                        String url = "C_Product?btAction=Pro_Search&txtSearch=";
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //ket thuc xu ly san pham
            //String action = request.getParameter("action");
            String action = request.getParameter("btAction");
            if (action == null) {
                RequestDispatcher rd = request.getRequestDispatcher("Controller?btAction=menuFunction");
                rd.forward(request, response);
            } else if (request.getParameter("username") == "") {
                RequestDispatcher rd = request.getRequestDispatcher(homePage);
                rd.forward(request, response);
            } else if (action.equals("qlsp")) {
                User u = UserDAO.GetInfo(request.getParameter("username"));
                if (u.getLoai() == 2 || u.getLoai() == 4) {
                    List<SanPham> result_pro = ProductDAO.View();
                    request.setAttribute("INFO", result_pro);
                    String title = "Quản lý sản phẩm";
                    request.setAttribute("title", title);
                    RequestDispatcher rd = request.getRequestDispatcher(productPage);
                    rd.forward(request, response);
                } else {
                    RequestDispatcher rd = request.getRequestDispatcher(notAlowPage);
                    rd.forward(request, response);
                }
            } else if (action.equals("Pro_Search")) {

                List<SanPham> result = ProductDAO.Search(request.getParameter("txtSearch"));
                request.setAttribute("INFO", result);
                String title = "Quản lý sản phẩm";
                request.setAttribute("title", title);
                RequestDispatcher rd = request.getRequestDispatcher(productPage);
                rd.forward(request, response);

            } else if (action.equals("Pro_Delete")) {

                int pid = Integer.parseInt(request.getParameter("product_id"));
                ProductDAO.Delete(pid);
                String url = "C_Product?btAction=Pro_Search&txtSearch=" + request.getParameter("txtSearch");
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);

            } else if (action.equals("Pro_Insert")) {
                SanPham p = new SanPham();
                p.setTensp(request.getParameter("txtsp"));
                p.setDongia(Float.parseFloat(request.getParameter("txtdongia")));
                p.setSoluong(Integer.parseInt(request.getParameter("txtsoluong")));
                int mancc = Integer.parseInt(request.getParameter("mancc"));
                int malsp = Integer.parseInt(request.getParameter("maloaisp"));
                ProductDAO.Insert(p, mancc, malsp);
                String url = "C_Product?btAction=Pro_Search&txtSearch=";
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);

            } else if (action.equals("Pro_Update")) {
                int pid = Integer.parseInt(request.getParameter("masp"));
                SanPham p = ProductDAO.GetInfo(pid);
                if (p != null) {
                    p.setTensp(request.getParameter("txtsp"));
                    p.setDongia(Float.parseFloat(request.getParameter("txtdongia")));
                    p.setSoluong(Integer.parseInt(request.getParameter("txtsoluong")));
                    LoaiSanPham lsp = ProductCategoryDAO.GetInfo(Integer.parseInt(request.getParameter("maloaisp")));
                    p.setLoaiSanPham(lsp);
                    NhaCungCap ncc = SupplierDAO.GetInfo(Integer.parseInt(request.getParameter("mancc")));
                    p.setNhaCungCap(ncc);
                    ProductDAO.Update(p);
                    String url = "C_Product?btAction=Pro_Search&txtSearch=";
                    RequestDispatcher rd = request.getRequestDispatcher(productPage);
                    rd.forward(request, response);
                }

            } else if (action.equals("Pro_Details_Update")) {
                List<NhaCungCap> lSup = SupplierDAO.View();
                request.setAttribute("lSup", lSup);
                List<LoaiSanPham> lProCate = ProductCategoryDAO.View();
                request.setAttribute("lProCate", lProCate);
                int pid = Integer.parseInt(request.getParameter("masp"));
                SanPham p = ProductDAO.GetInfo(pid);
                request.setAttribute("DETAILS", p);
                String title = "Sửa sản phẩm";
                request.setAttribute("title", title);
                RequestDispatcher rd = request.getRequestDispatcher(insert_updatePagePro);
                rd.forward(request, response);

            } else if (action.equals("Pro_Details_Insert")) {
                List<NhaCungCap> lSup = SupplierDAO.View();
                request.setAttribute("lSup", lSup);
                List<LoaiSanPham> lProCate = ProductCategoryDAO.View();
                request.setAttribute("lProCate", lProCate);
                request.setAttribute("INSERT", "insert");
                String title = "Thêm sản phẩm mới";
                request.setAttribute("title", title);
                RequestDispatcher rd = request.getRequestDispatcher(insert_updatePagePro);
                rd.forward(request, response);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
